<template>
    <div>
        <h2>文件上传</h2>
        <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :headers="uploadHeaders"
            :on-change="handleFileChange"
            limit="1"
        >
            <template #trigger>
                <el-button type="primary">选择文件</el-button>
            </template>
        </el-upload>
        <el-button class="ml-3" type="success" @click="uploadFiles">
            上传
        </el-button>
        <el-list>
            <el-list-item v-for="(response, index) in responses" :key="index">
                {{ response }}
            </el-list-item>
        </el-list>
        <div v-if="fileContent" v-html="fileContent" class="preview"></div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploadInstance } from 'element-plus'
import axios from "axios";

const uploadRef = ref<UploadInstance | null>(null)
const files = ref([])
const responses = ref([])
const fileContent = ref('')

const uploadHeaders = {
    Authorization: `Bearer ${localStorage.getItem('token')}`
}

const handleFileChange = (file, fileList) => {
    files.value = fileList.map(f => f.raw)
    if (files.value.length > 0) {
        previewFile(files.value[0])
    }
}

const previewFile = (file) => {
    const reader = new FileReader()
    reader.onload = (e) => {
        fileContent.value = e.target.result
    }
    reader.readAsText(file)
}

const uploadFiles = async () => {
    if (files.value.length === 0) {
        alert('请选择一个文件')
        return
    }

    const formData = new FormData()
    formData.append('file', files.value[0])

    try {
        const response = await axios.post('http://localhost:8082/files/upload', formData, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
            }
        })
        console.log(response)
        if(response.code === 200) {
            alert(response.data)
        }else{
            alert(response.message)
        }
    } catch (error) {
        console.error('错误:', error)
        alert('文件上传失败')
    }
}

</script>

<style>
.upload-demo {
    margin-bottom: 20px;
}
.ml-3 {
    margin-left: 10px;
}
/*.preview {*/
/*    margin-top: 20px;*/
/*    border: 1px solid #ccc;*/
/*    padding: 10px;*/
/*}*/
.preview #big {
    margin-left: 200px; /* 距离左边200px */
    margin-top: 200px; /* 距离顶部200px */
}
.preview .BIGBIG {
    margin-left: 200px; /* 距离左边200px */
    margin-top: 200px; /* 距离顶部200px */
}
</style>
